/*
 * @Description: 实现数字证书的原理
 * @Version: 1.0
 * @Autor: ziwei
 * @Date: 2021-09-17 17:37:50
 * @LastEditors: ziwei
 * @LastEditTime: 2021-09-17 17:51:10
 */
let {generateKeyPairSync, createVerify,createSign,createHash} = require('crypto');
let serverRSA = generateKeyPairSync('rsa',{
  modulusLength:1024,
  publicKeyEncoding:{
    type:'spki',
    format:'pem',//base64格式的私钥
  },
  privateKeyEncoding:{
    type:'pkcs8',//公钥
    format:'pem',
    cipher:'aes-256-cbc',
    passphrase:'passphrase'
  }
});
let caRSA = generateKeyPairSync('rsa',{
  modulusLength:1024,
  publicKeyEncoding:{
    type:'spki',
    format:'pem',//base64格式的私钥
  },
  privateKeyEncoding:{
    type:'pkcs8',//公钥
    format:'pem',
    cipher:'aes-256-cbc',
    passphrase:'passphrase'
  }
});

const info = {
  domain:'http://127.0.0.1:8080',
  publicKey:serverRSA.publicKey
}
//把申请信息发送给CA机构请求颁发证书
//实现的时候签名的并不是Info,而是hash,性能很差，一般不能计算大量的数据
let hash = createHash('sha256').update(JSON.stringify(info)).digest('hex');
let sign = getSign(hash,caRSA.privateKey,passphrase);
let cert = {
  info,
  sign//CA的签名
}//这是为了证书了，客户端会先验证证书的，用CA的公钥验证证书的合法性，然后取出公钥
let valid = verifySign(hash,sign,caRSA.publicKey);
console.log("浏览器验证CA的签名",valid);

function getSign(content,privateKey,passphrase) {
  let signObj = createSign('RSA-SHA256');
  signObj.update(content);
  return signObj.sign({
    key:privateKey,
    format:'pem',
    passphrase
  },'hex')
}
function verifySign(content,sign,publicKey) {
  var verifyObj = createVerify("RSA-SHA256");
  verifyObj.update(content)
  return verifyObj.verify(publicKey,sign,'hex')
}